﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Web.Framework;
using System.IO;
using Web.Framework.Translate;
using Web.CrmContacto.Code;
using Web.Framework.Svc;
using System.Configuration;
using CrmContacto.Contracts.Contracts;
using CrmContacto.WebApp.Code.InnerClasses;
using System.Web.Caching;

namespace CrmContacto.WebApp.Handler
{
    /// <summary>
    /// Summary description for FileUploadEmailResult
    /// </summary>
    public class FileUploadEmailResult : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string response = LocalizationProvider.Instance["Bo.Excel.Contacto.ArchivoProcesadoCorrectamente"];
            string filePath = string.Empty;
            List<string> parseErrors = new List<string>();
            try
            {
                string fileName = Path.GetFileName(context.Request.Files[0].FileName);
                string tmpPath = HttpContext.Current.Server.MapPath("/Tmp");
                fileName = fileName + Guid.NewGuid().ToString();
                filePath = Path.Combine(tmpPath, fileName);
                context.Request.Files[0].SaveAs(filePath);

                WebServiceHelper webServiceHelper = new WebServiceHelper();
                webServiceHelper.ServiceOptionsDefault = new ServiceOptions();
                webServiceHelper.ServiceOptionsDefault.UserName = Convert.ToString(context.User.Identity.Name);
                webServiceHelper.ServiceOptionsDefault.CompanyId = BasePage.CompanyId;

                int accionDeMarketingComunicacionId = Convert.ToInt32(context.Request.QueryString["Id"]);
                List<AccionDeMarketingEmailResultado> resultadoList = ExcelHelper.ObtenerResultadosEmail(filePath, accionDeMarketingComunicacionId);

                resultadoList = webServiceHelper.SaveResultadosEmailAccionDeMarketing(accionDeMarketingComunicacionId, resultadoList);

                // Guardo en sessión lo procesado para que se vea desde la pantalla                
                context.Cache.Add(context.Session.SessionID + MiscClass.EmailMarketingImportRecordsKey, resultadoList, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0), CacheItemPriority.Low, null);
                //context.Session[MiscClass.EmailMarketingImportRecordsKey] = resultadoList;

            }     
            catch (Exception ex)
            {
                response = ex.Message;
                ExceptionManager.Instance.HandleException(ex);
            }
            finally
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }

            context.Response.ClearContent();
            context.Response.Write(response);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}